<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.supplier.type" style="width: 120px">
            <el-option label="供应商名称" value="supplier_name"></el-option>
            <el-option label="供应商ID" value="supplier_code"></el-option>
            <el-option label="供应商编码" value="supplier_coding"></el-option>
          </el-select>
          <VBatchInput v-model="form.supplier.value" @search="query" class="w-60" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.user.type" style="width: 130px">
            <el-option label="添加人员" value="create_user_id"></el-option>
            <el-option label="开发人员" value="develop_id"></el-option>
            <el-option label="海外仓采购" value="oversea_purchase_id"></el-option>
            <el-option label="FBA采购" value="fba_purchase_id"></el-option>
            <el-option label="供应商负责人" value="director_id"></el-option>
          </el-select>
          <VCascader v-model="form.user.value" placeholder="人员" multiple collapse-tags filterable clearable
            style="min-width: 160px" />
        </VGroup>
        <VSelect v-model="form.audit_status" placeholder="审核状态" :options="options.audit_status" multiple collapse-tags
          style="min-width: 160px" select/>
        <VSelect v-model="form.is_temporary" placeholder="临时供应商" :options="options.is_temporary" multiple collapse-tags
          style="width: 160px" />
        <VCascader v-model="form.company_category" placeholder="分类" type="2" multiple collapse-tags filterable
          clearable style="min-width: 160px"/>
        <VGroup>
          <div class="v-group-item">更新时间</div>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
        <teleport v-if="demandTabsLoad" to="#demand-tabs">
          <el-tabs v-model="form.type" @tab-change="tabChange">
            <el-tab-pane v-for="(d, i) in options.type" :key="i" :label="`${d.label}(${d.num || 0})`" :name="d.value"></el-tab-pane>
          </el-tabs>
        </teleport>
      </template>
      <template #toolbar_btns>
        <div id="demand-tabs" class="w-full" v-dom-load="() => demandTabsLoad = true"></div>
        <VButton auth="/purchase/supplier/data/add" type="primary" @click="create(tableRef)"><i class="dk-iconfont icon-Plus" />添加</VButton>
        <VAudit field="s_id" url="/v1/supplier/supplier/batch-audit"
          :auth="['/purchase/supplier/data/purchasing_manager_audit', '/purchase/supplier/data/purchasing_director_audit', '/purchase/supplier/data/development_manager_audit', '/purchase/supplier/data/finance_audit']"
          :tableRef="tableRef" :list="options.batch_audit_status" @success="query" />
        <VButton auth="/purchase/supplier/data/submit" :loading="loadings.submit" @click="handleBatch('submit')">批量提交
        </VButton>
        <VButton auth="/purchase/supplier/data/edit" :loading="loadings.submit" @click="handleBatch('edit')">批量修改
        </VButton>
        <VButton auth="/purchase/supplier/data/saihe" :loading="loadings.saihe" @click="handleBatch('saihe')">手动同步赛盒数据
        </VButton>
        <VButton auth="/purchase/supplier/data/changeLog" :loading="loadings.saihe" @click="() => changeListRef.open()">税点账期变更记录
        </VButton>
        <!-- <VButton auth="/purchase/supplier/data/saihe" :loading="loadings.saihePush" @click="handleBatch('saihePush')">手动推送赛盒数据
        </VButton> -->
        <VExport auth="/purchase/supplier/data/export" :name="name" mainKey="s_id" :tableRef="tableRef" task class="ml-auto" />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <ChangeList ref="changeListRef"  :options="options" />
    <Audit ref="auditRef" @success="query" />
    <Edit ref="editRef" :options="options" @success="query" />
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add/index'
import Audit from './components/Audit'
import ChangeList from './components/ChangeList'
import Edit from './components/Edit'
import { getOption } from '@/api/public'
import { ElMessage } from 'element-plus'
import { resMessage } from '@/utils/res'
const name = 'supplier'
const tableRef = ref()
const logRef = ref()
const changeListRef = ref()
const loadings = reactive({})
const demandTabsLoad = ref(false);
// 查询
const query = () => {
  tableRef?.value.query()
}
// 获取options
const options = ref({})
const total = ref({});
getOption({ type: name }).then(res => {
  options.value = res.data
  // options.value.type = [
  //   {"label": "全部","value": 0},
  //   {"label": "待提交","value": 1},
  //   {"label": "待采购经理审核","value": 2},
  //   {"label": "待采购总监审核","value": 3},
  //   {"label": "待开发经理审核","value": 4},
  //   {"label": "已审核","value": 5},
  //   {"label": "已驳回","value": 6},
  //   {"label": "待核算会计审核","value": 7},
  // ]
  // 测试数据
  options.value.test = [{ label: '1', value: '1' }]
  getTotal();
})

// 获取状态数量
const getTotal = async (params = { type: 0 }) => {
  if (!options.value.type) return
  await api.total(params).then(res => {
    options.value.type.forEach(t => {
      t.num = res.data.find(d => d.value === t.value)?.num || 0
    })
  })
}
const tabValue = ref(0);
const tabChange = (name) => {
  tabValue.value = name;
  query();
};
// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 批量操作
const editRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const s_ids = selection.map(d => d.s_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    edit: () => {
      editRef?.value.open(s_ids)
    },
    submit: () => {
      showLoading()
      api.batchSubmit({ s_ids }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
    saihe: () => {
      showLoading()
      api.saihe({ s_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    saihePush: () => {
      showLoading()
      api.saihePush({ s_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
  }
  handle[name]()
}

// 单行操作
const handleRow = (name, row, rowIndex) => {
  const { s_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    submit: () => {
      showLoading()
      api.submit({ s_id }).then(res => {
        ElMessage.success('操作成功')
        query()
      }).finally(closeLoading)
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 136 },
  formConfig: {
    data: {
      type: 0,
      supplier: { type: 'supplier_name', value: '' }, // 组合
      user: { type: 'create_user_id', value: '' }, // 组合
      is_temporary: [],
      dateRange: { type: 'update_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 60 },
    {
      title: '供应商类型', minWidth: 180, slots: {
        default: ({ row }) => {
          const { purchase_type_name, payment_type_name, supplier_level_name, is_blacklist_name, status_name, company_category_name } = row
          return < div >
            <VText title='供应商类型' value={purchase_type_name}></VText>
            <VText title='付款方式' value={payment_type_name}></VText>
            <VText title='供应商级别' value={supplier_level_name}></VText>
            <VText title='是否黑名单' value={is_blacklist_name}></VText>
            <VText title='是否启用' value={status_name}></VText>
            <VText title='供应商类型' value={company_category_name}></VText>
          </div >
        }
      }
    },
    {
      title: '供应商信息', minWidth: 280, slots: {
        default: ({ row }) => {
          const { supplier_code,supplier_coding, supplier_name, company_address, factory_address, is_temporary_name } = row
          return < div >
            <VText title='供应商id' value={supplier_code} />
            <VText title='供应商编码' value={supplier_coding} />
            <VText title='名称' value={supplier_name} />
            <VText title='公司地址' value={company_address} />
            <VText title='工厂地址' value={factory_address} />
            <VText title='是否临时供应商' value={is_temporary_name} />
          </div >
        }
      }
    },
    {
      title: '联系信息', minWidth: 160, slots: {
        default: ({ row }) => {
          const { name, tel } = row
          return < div >
            <VText title='联系人' value={name}></VText>
            <VText title='手机' value={tel}></VText>
          </div >
        }
      }
    },
    {
      title: '付款信息', minWidth: 260, slots: {
        default: ({ row }) => {
          const { payee, period_name, is_invoice_name } = row
          return < div >
            <VText title='账户名' value={payee} />
            <VText title='结算方式' value={period_name} />
            <VText title='是否开票' value={is_invoice_name} />
          </div >
        }
      }
    },
    {
      title: '操作人员', minWidth: 200, slots: {
        default: ({ row }) => {
          const { create_user, develop_name, oversea_purchase, fba_purchase, director_name } = row
          return < div >
            <VText title='添加人员' value={create_user}></VText>
            <VText title='开发人员' value={develop_name}></VText>
            <VText title='海外仓采购' value={oversea_purchase}></VText>
            <VText title='FBA采购' value={fba_purchase}></VText>
            <VText title='供应商负责人' value={director_name}></VText>
          </div >
        }
      }
    },
    {
      title: '操作时间', minWidth: 230, slots: {
        default: ({ row }) => {
          const { create_time, update_time, audit_time } = row
          return < div >
            <VText title='创建时间' value={create_time}></VText>
            <VText title='审核时间' value={audit_time}></VText>
            <VText title='修改时间' value={update_time}></VText>
          </div >
        }
      }
    },
    {
      title: '供应商状态', minWidth: 200, slots: {
        default: ({ row }) => {
          const { audit_status_name, audit_remark } = row
          return < div >
            <VText title='审核状态' value={audit_status_name}></VText>
            <VText title='审核驳回原因' value={audit_remark}></VText>
          </div >
        }
      }
    },
    {
      field: 'remark', title: '备注', minWidth: 120, slots: {
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      title: '操作', width: 100, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { s_id, audit_status } = row
          // 审核状态1待提交2待采购经理审核3待采购总监审核4待开发经理审核5已审核6已驳回
          return [<div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            <VButton auth="/purchase/supplier/data/view" link type="primary" onClick={() => addRef?.value.open(s_id, true)}>查看</VButton>
            {[1, 5, 6].includes(audit_status) ? <VButton auth="/purchase/supplier/data/edit" link type="primary" onClick={() => addRef?.value.open(s_id)}>编辑</VButton> : ''}
            {[1, 6].includes(audit_status) ? <VButton auth="/purchase/supplier/data/submit" link type="primary" loading={loadings['submit' + rowIndex]} onClick={() => handleRow('submit', row, rowIndex)}>提交</VButton> : ''}
            <VButton auth="/purchase/supplier/data/logs" link type="primary" onClick={() => logRef?.value.open({ XDEBUG_SESSION_START: 'PHPSTORM', log_type: name, s_id })}>日志</VButton>
          </div>]
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page, form }) => {
        await getTotal({ ...form, ...page })
        return api.query({ ...form, ...page }).then(res => {
          options.value.type.forEach(d => {
            if (d.value === tabValue.value) {
              d.num = res.total
            }
          })
          return res
        })
      }
    }
  }
})
</script>